import pandas as pd
from collections import Counter
import re
from pyecharts.charts import *
from pyecharts.charts import WordCloud
from pyecharts import options as opts
from pyecharts.globals import ThemeType
from pyecharts.charts import Page

df = pd.read_csv("result_1.csv")
df.head()  # 读取全部数据

# b站评分20电影评论数
res = df.sort_values(by='评分', ascending=False)
res = res.sort_values(by='短评数', ascending=False).head(20)
top10_score_num = res['评分人数'].values.tolist()
top10_score_title = res['标题'].values.tolist()
top10_score_short = res['短评数'].values.tolist()
# print(top10_score_num)
# print(res)

# b站评论前十电影推荐（热议）
res = df.sort_values(by='短评数', ascending=False).head(20)
cmt10_short_num = res['短评数'].values.tolist()
cmt10_long_num = res['长评数'].values.tolist()
cmt_title = res["标题"].values.tolist()
# print(cmt10_short_num)
# print(cmt10_long_num)
# print(cmt_title)

# b站各标签电影占比
res = ','.join(df['标签'].values.tolist())
res_list = res.split(',')
types_list = []
values_list = []
# counter = Counter(res_list)
# for element, count in counter.items():
#     # print(f"{element}: {count}")
#     types_list.append(element)
#     values_list.append(count)
series = pd.Series(res_list)
res = series.value_counts()
flag = 0
other = 0
types_all = []
values_all = []
for index, value in res.items():
    types_all.append(index)
    values_all.append(value)
    if flag < 13:
        types_list.append(index)
        values_list.append(value)
    else:
        other += value
    flag += 1
# 追加其他
types_list.append("其他")
values_list.append(other)

# print(types_list[0:10])  # 获取前10个
# print(values_list)
# print(len(values_list)) # 65
# print(values_list[0:10])


# b站电影关键词
key_list = []
for i in range(len(types_all)):
    key_list.append((types_all[i], values_all[i]))
# print(key_list)


bar1 = (
    Bar()
    .add_xaxis(xaxis_data=top10_score_title)
    .add_yaxis(y_axis=top10_score_num,
               itemstyle_opts=opts.ItemStyleOpts(color='cornflowerblue'),  # 颜色
               series_name='评分人数')
    .set_global_opts(
        title_opts=opts.TitleOpts(title='b站评分前20电影评论数', subtitle='评分均为9.9', pos_left="10%"),
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-15)),
    )
)

# 生成render.html
bar1.render('html/score.html')

# 评论前十
bar2 = (
    Bar({"theme": ThemeType.MACARONS})
    .add_xaxis(cmt_title)
    .add_yaxis("短评数", cmt10_short_num)
    .add_yaxis("长评数", cmt10_long_num)
    .set_global_opts(
        # 通过字典对标题配置
        # title_opts={"text": "b站评论前十电影推荐", "subtext": "正在热议", "pos_left": "20%"}
        title_opts=opts.TitleOpts(title='b站评论前十电影推荐', subtitle='网友正在热议', pos_left="15%"),
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-15))
    )
)
bar2.render("html/cmt_bar.html")

# b站各标签电影占比
pie = (
    Pie()
    .add(
        '人数',
        [list(z) for z in zip(types_list, values_list)],
        radius=['30%', '75%'],
        center=['50%', '50%'],
        rosetype='radius',
        label_opts=opts.LabelOpts(is_show=False),
    )
    .set_global_opts(title_opts=opts.TitleOpts(title='b站各标签电影占比', pos_left='40%'),
                     legend_opts=opts.LegendOpts(type_="scroll", pos_top="20%", pos_left="85%",
                                                 orient="vertical"))  # 图例配置项
    .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}:{c} {d}%"))  # 显示百分比
)
pie.render("html/pie.html")

# 词云图
cloudObj = WordCloud()
# shap默认为cicrle，其他形状有circle, cardioid, diamond, triangle-forward, triangle, pentagon, star
cloudObj.add('', key_list, shape='triangle')
cloudObj.set_global_opts(title_opts=opts.TitleOpts(title="b站电影关键词"))
cloudObj.render('html/word.html')

# shap可更换为图片，但尝试后效果不好。图片存在bug，需刷新网页后才会显示。
# cloudObj.add('', data, mask_image='C:\XXX.png')

# # 创建page对象
# page = Page(layout=Page.DraggablePageLayout)
# page.add(bar1, bar2, cloudObj, pie)
# page.render("html/page.html")

# 组合整个图
# Page.save_resize_html('html/page.html', cfg_file='html/config.json', dest="html/bilibili电影数据可视化.html")